package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    //注入spring容器中加载配置文件的value值(需要传入key值，即配置文件的key)
    //生成的静态页面存放的目录
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //调用service层方法，添加检查套餐的基本数据
        setmealDao.addSetmeal(setmeal);
        //添加检查套餐和检查组的对应关系
        Integer setmealId = setmeal.getId();
        addSetmealAndCheckGroup(setmealId,checkgroupIds);

        //将图片文件名存入redis数据库中()
        String img = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);

        //此时数据库中的数据已经改变了，就需要重新生成手机端套餐和套餐详情静态页面
        getMobileStaticHtml();
    }

    //生成手机端套餐和套餐详情的静态页面
    public void getMobileStaticHtml() {
        //第一步：查询数据库，获取最新的套餐信息(此信息只是套餐的基本信息)
        List<Setmeal> list = setmealDao.findAll();
        //第二步：生成套餐列表静态页面
        getStaticSetmealHtml(list);
        //第三步：生成套餐详情静态页面
        getStaticSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void getStaticSetmealHtml(List<Setmeal> list) {
        //调用生成静态文件模板方法前，准备所需的数据
        String templateName = "setmeal.ftl";
        String htmlName = "setmeal_static.html";
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList",list);
        getStaticHtml(templateName,htmlName,map);
    }

    //生成套餐详情静态页面
    public void getStaticSetmealDetailHtml(List<Setmeal> list) {
        //调用生成静态文件模板方法前，准备所需的数据
        //所需数据应该为每个检查套餐的详细数据(此时传入的是所有的套餐基本信息)
        //所有的套餐详情静态页面都是一样的模板
        String templateName = "setmeal_detail.ftl";
        for (Setmeal setmeal : list) {
            //根据套餐id查询此套餐的详细信息
            Setmeal setmealInfo = setmealDao.findInfoById(setmeal.getId());

            System.out.println(setmealInfo);

            Map<String, Object> map = new HashMap<>();
            map.put("setmeal",setmealInfo);

            //生成的静态文件的名字
            String htmlName = "setmeal_detail_"+setmeal.getId()+".html";

            //调用生成静态页面的模板方法
            getStaticHtml(templateName,htmlName,map);
        }
    }

    //生成静态页面模板方法
    //template.process(map,writer);
    public void getStaticHtml(String templateName,String htmlName,Map<String,Object> map){
        //获取freemarker配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            //获取模板对象
            Template template = configuration.getTemplate(templateName);

            //获取输出流指向生成的文件
            //writer = new FileWriter(new File(outPutPath+"/"+htmlName));

            writer = new OutputStreamWriter(new FileOutputStream(outPutPath + "/" + htmlName), "utf-8");
            template.process(map,writer);
            System.out.println("一个静态页面生成完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用pageHelper
        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> page = setmealDao.findPage(queryString);

        long total = page.getTotal();
        List<Setmeal> result = page.getResult();
        return new PageResult(total,result);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findInfoById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        System.out.println("service中的findSetmealCount执行了。。。");
        return setmealDao.findSetmealCount();
    }

    @Override
    public String findNameById(Integer setmealId) {
        return setmealDao.findNameById(setmealId);
    }


    //添加检查套餐和检查组的对应数据
    public void addSetmealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
        //判断数据是否为空
        if(checkgroupIds!=null && checkgroupIds.length>0){
            Map<String,Integer> map = new HashMap<String,Integer>();
            map.put("setmeal_id",setmealId);
            for (Integer checkgroupId : checkgroupIds) {
                map.put("checkgroup_id",checkgroupId);
                setmealDao.addSetmealAndCheckGroup(map);
            }
        }
    }
}
